package com.zlt.util;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

public class ClassUtil {

    /**
     * 反射将值注入到对象中
     *
     * @param obj
     * @param name
     * @param value
     */
    public static void setValue(Object obj, String name, String value) {
        Class<?> clazz = obj.getClass();
        try {
            Field declaredField = clazz.getDeclaredField(name);
            declaredField.setAccessible(true);
            Class<?> type = declaredField.getType();
            if (type == int.class || type == Integer.class) {
                declaredField.set(obj, Integer.parseInt(value));
            } else if (type == long.class || type == Long.class) {
                declaredField.set(obj, Long.parseLong(value));
            } else if (type == double.class || type == Double.class) {
                declaredField.set(obj, Double.parseDouble(value));
            } else {
                declaredField.set(obj, value);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从请求中解析参数得到对象
     *
     * @param clazz
     * @param request
     * @param <T>
     * @return
     */
    public static <T> T resolveRequest(Class<T> clazz, HttpServletRequest request) {
        try {
            T t = clazz.newInstance();
            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
            for (Map.Entry<String, String[]> entry : entries) {
                setValue(t, entry.getKey(), entry.getValue()[0]);
            }
            return t;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
